from datetime import datetime

from pydantic import BaseModel, Field, field_validator

from forward.utils.tools import ToolsUtil


class BaseSchema(BaseModel):
    @field_validator("*", mode="before")
    def empty_str_to_none(cls, v):
        if v == "":
            return None
        return v

    model_config = {
        "alias_generator": ToolsUtil.to_lower_camel,
        "populate_by_name": True,
        "json_encoders": {datetime: lambda dt: dt.strftime("%Y-%m-%d %H:%M:%S")},
    }


class RecordeMixinSchema(BaseModel):
    created_time: datetime | None = Field(default=None, description="创建时间")
    updated_time: datetime | None = Field(default=None, description="更新时间")
    deleted_time: datetime | None = Field(default=None, description="删除时间")
    created_by: str | None = Field(default=None, description="创建者")
    updated_by: str | None = Field(default=None, description="更新者")
    deleted_by: str | None = Field(default=None, description="删除者")
    is_deleted: int | None = Field(default=None, description="是否删除")

    model_config = {
        "alias_generator": ToolsUtil.to_lower_camel,
        "populate_by_name": True,
    }
    # model_config=ConfigDict(
    #     json_encoders={datetime: lambda dt: dt.strftime("%Y-%m-%d %H:%M:%S")}
    # )

    # @field_validator("created_time", "updated_time", "deleted_time", mode="after")
    # @classmethod
    # def format_datetime(cls, v):
    #     if not v:
    #         return None
    #     if isinstance(v, datetime):
    #         return v.strftime("%Y-%m-%d %H:%M:%S")
    #     return v

    # def model_dump(self, *args, **kwargs):
    #     data = super().model_dump(*args, **kwargs)
    #     if "created_time" in data and isinstance(data["created_time"], datetime):
    #         data["created_time"] = data["created_time"].strftime("%Y-%m-%d %H:%M:%S")
    #     if "updated_time" in data and isinstance(data["updated_time"], datetime):
    #         data["updated_time"] = data["updated_time"].strftime("%Y-%m-%d %H:%M:%S")
    #     if "deleted_time" in data and isinstance(data["deleted_time"], datetime):
    #         data["deleted_time"] = data["deleted_time"].strftime("%Y-%m-%d %H:%M:%S")
    #     return data
